package com.pen.interfece.controller.eye;

import cn.hutool.http.HttpUtil;
import com.alibaba.dashscope.common.History;
import com.alibaba.fastjson.JSON;
import com.pen.interfece.pojo.Result;
import com.pen.interfece.pojo.dto.AlgoResDTO;
import com.pen.interfece.pojo.entity.userLogin;
import com.pen.interfece.pojo.history;
import com.pen.interfece.pojo.historyRequest;
import com.pen.interfece.service.illService;
import com.pen.interfece.util.FileUtils;
import com.pen.interfece.util.JwtUtil;
import com.pen.interfece.util.ThreadLocalUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.sql.Time;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;



@RestController
@RequestMapping("/check")
@Slf4j
public class EyeCheckController {

    @Autowired
    private FileUtils fileUtils;
    @Autowired
    private illService llService;

    @Value("${sys.ai_eye_algo_server_stream}")
    private String eyeAlgoStreamAddr;

    /**
     * AI眼病检测（逐个上传多张图片）
     */
    @PostMapping(value = "/stream/ai/eye/illness", consumes = "multipart/form-data")
    public Result<List<Map<String, Object>>> checkByStream(
            @RequestParam("images") List<MultipartFile> images) {

        log.info("收到 {} 张图片进行AI检测", images.size());

        // 1. 参数校验
        if (images == null || images.isEmpty()) {
            return Result.error("请上传至少一张图片！");
        }

        List<Map<String, Object>> resultList = new ArrayList<>();

        // 2. 逐个处理每张图片
        for (MultipartFile image : images) {
            Map<String, Object> resultMap = new HashMap<>();
            resultMap.put("imageName", image.getOriginalFilename());

            File tempFile = null;
            try {
                // 2.1 转换为临时文件（自动处理后缀）
                tempFile = convertToTempFile(image);

                // 2.2 构建请求参数
                HashMap<String, Object> params = new HashMap<>();
                params.put("image", tempFile); // 关键参数名必须与服务端一致

                // 2.3 发送HTTP请求
                String response = HttpUtil.createPost(eyeAlgoStreamAddr)
                        .contentType("multipart/form-data")
                        .form(params)
                        .execute()
                        .body();

                log.debug("图片 {} 响应原始数据: {}", image.getOriginalFilename(), response);

                // 2.4 处理响应
                handleAlgoResponse(response, resultMap);

            } catch (IOException e) {
                log.error("图片 {} 转换失败", image.getOriginalFilename(), e);
                resultMap.put("error", "文件处理异常: " + e.getMessage());
            } catch (Exception e) {
                log.error("图片 {} 处理异常", image.getOriginalFilename(), e);
                resultMap.put("error", "系统错误: " + e.getMessage());
            } finally {
                // 2.5 清理临时文件
                if (tempFile != null && tempFile.exists()) {
                    boolean deleted = tempFile.delete();
                    if (!deleted) {
                        log.warn("临时文件删除失败: {}", tempFile.getAbsolutePath());
                    }
                }
            }

            resultList.add(resultMap);
        }

        return Result.success(resultList);
    }

    /**
     * 处理算法响应
     */
    private void handleAlgoResponse(String response, Map<String, Object> resultMap) {
        if (!StringUtils.hasLength(response)) {
            resultMap.put("error", "算法服务无响应");
            return;
        }

        try {
            AlgoResDTO algoResDTO = JSON.parseObject(response, AlgoResDTO.class);
            if (algoResDTO == null) {
                resultMap.put("error", "响应解析失败");
            } else if (!algoResDTO.isSuccess()) {
                resultMap.put("error", algoResDTO.getMsg());
            } else {
                resultMap.put("result", algoResDTO.getData());
            }
        } catch (Exception e) {
            log.error("响应解析异常: {}", response, e);
            resultMap.put("error", "响应数据格式错误");
        }
    }

    /**
     * 将MultipartFile转换为临时文件（自动保留后缀）
     */
    private File convertToTempFile(MultipartFile multipartFile) throws IOException {
        String originalFilename = multipartFile.getOriginalFilename();
        String suffix = ".jpg"; // 默认后缀

        // 从原始文件名提取后缀（如 .png, .jpeg 等）
        if (originalFilename != null && originalFilename.contains(".")) {
            suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        }

        // 创建带明确后缀的临时文件
        File tempFile = File.createTempFile("ai_eye_", suffix);
        multipartFile.transferTo(tempFile);
        return tempFile;
    }

    @PostMapping("/history")
    public Result saveHistory(HttpServletRequest request, HttpServletResponse response, Object handler,
                              @RequestParam("name") String name,
                              @RequestParam("detail") String detail,
                              @RequestParam("methods") String methods,
                              @RequestParam("confidence") String confidence,

                              @RequestParam("file") MultipartFile file) throws IOException {


        String imgPath = fileUtils.saveImage(file);

        // 构建 history 对象
        history history = new history();
        history.setName(name);
        history.setDetail(detail);
        history.setMethods(methods);
        history.setConfidence(confidence);

        history.setTime(LocalDateTime.now());
        history.setImg(imgPath);  // 存储图片路径



        String token=request.getHeader("token");
        Map<String, Object> claims = JwtUtil.parseToken(token);
        history.setUserid((int)claims.get("userId"));




        llService.add(history);
        return Result.success();
    }
}